package com.jcfk.eam.service.mould;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.mould.EamMouldLifetimeRecordDao;
import com.jcfk.eam.domain.dto.mould.EamMouldLifetimeRecordDTO;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.po.mould.EamMouldLifetimeRecord;
import com.jcfk.eam.domain.query.mould.EamMouldLifetimeRecordQuery;
import com.jcfk.eam.service.main.EamAssetInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 模具使用寿命
 *
 * @author yrl
 * @email
 * @date 2025-07-14
 */
@Service
public class EamMouldLifetimeRecordService extends BaseService<EamMouldLifetimeRecordDao, EamMouldLifetimeRecord> {

    private final EamAssetInfoService eamAssetInfoService;

    public EamMouldLifetimeRecordService(EamAssetInfoService eamAssetInfoService) {
        this.eamAssetInfoService = eamAssetInfoService;
    }

    /**
     * EamMouldLifetimeRecord分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamMouldLifetimeRecordDTO> queryByPage(DataPage<EamMouldLifetimeRecordDTO> page, EamMouldLifetimeRecordQuery query) {
        // 分页查询
        query.setAssetCode(StringUtils.isEmpty(query.getAssetCode()) ? query.getAssetCode() : query.getAssetCode() + "%");
        query.setAssetName(StringUtils.isEmpty(query.getAssetName()) ? query.getAssetName() : query.getAssetName() + "%");
        query.setEquipCode(StringUtils.isEmpty(query.getEquipCode()) ? query.getEquipCode() : query.getEquipCode() + "%");
        query.setEquipName(StringUtils.isEmpty(query.getEquipName()) ? query.getEquipName() : query.getEquipName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamMouldLifetimeRecord是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamMouldLifetimeRecordDTO dto) {
        QueryWrapper<EamMouldLifetimeRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入模具使用寿命
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamMouldLifetimeRecordDTO dto) {

        // 保存
        EamMouldLifetimeRecord item = new EamMouldLifetimeRecord();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);
        item.setRegistrationTime(dto.getRegistrationTime() == null ? new Date() : dto.getRegistrationTime());
        EamAssetInfo assetInfo = eamAssetInfoService.getById(dto.getAssetId());
        if (assetInfo != null) {
            Integer cumulativeUseTimes = Optional.ofNullable(assetInfo.getCumulativeUseTimes()).orElse(0);
            long totalQuantity = cumulativeUseTimes + dto.getUseQuantity();
            item.setTotalQuantity(totalQuantity);
            assetInfo.setCumulativeUseTimes((int) totalQuantity);
            eamAssetInfoService.updateById(assetInfo);
        }

        super.save(item);
    }

    /**
     * 更新模具使用寿命
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamMouldLifetimeRecordDTO dto) {

        // 保存
        EamMouldLifetimeRecord item = new EamMouldLifetimeRecord();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }

    /**
     * 根据批量主键删除模具使用寿命(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamMouldLifetimeRecordDTO dto) {

        EamMouldLifetimeRecord item = new EamMouldLifetimeRecord();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamMouldLifetimeRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamMouldLifetimeRecord item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取模具使用寿命信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamMouldLifetimeRecordDTO get(String id) {
        // 查询数据
        EamMouldLifetimeRecord item = this.baseMapper.selectById(id);
        EamMouldLifetimeRecordDTO dto = new EamMouldLifetimeRecordDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamMouldLifetimeRecordDTO>
     */
    public List<EamMouldLifetimeRecordDTO> getList(EamMouldLifetimeRecordQuery query) {
        // 查询条件
        QueryWrapper<EamMouldLifetimeRecord> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getAssetId()), EamMouldLifetimeRecord::getAssetId, query.getAssetId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getAssetCode()), EamMouldLifetimeRecord::getAssetCode, query.getAssetCode());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getAssetName()), EamMouldLifetimeRecord::getAssetName, query.getAssetName());
        qw.lambda().eq(!StrUtil.isEmpty(query.getEquipId()), EamMouldLifetimeRecord::getEquipId, query.getEquipId());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getEquipCode()), EamMouldLifetimeRecord::getEquipCode, query.getEquipCode());
        qw.lambda().likeRight(!StrUtil.isEmpty(query.getEquipName()), EamMouldLifetimeRecord::getEquipName, query.getEquipName());
        qw.lambda().ge(!StrUtil.isEmpty(query.getRegistrationTimeStart()), EamMouldLifetimeRecord::getRegistrationTime, query.getRegistrationTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getRegistrationTimeEnd()), EamMouldLifetimeRecord::getRegistrationTime, query.getRegistrationTimeEnd());
        // 查询数据
        List<EamMouldLifetimeRecord> list = super.list(qw);

        return convertList(list, EamMouldLifetimeRecordDTO.class);
    }

    /**
     * 根据主键获取模具使用寿命信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        EamMouldLifetimeRecord item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        EamAssetInfo assetInfo = eamAssetInfoService.getById(item.getAssetId());
        if (assetInfo != null) {
            long lastCumulativeUseTimes = item.getTotalQuantity() - item.getUseQuantity();
            assetInfo.setCumulativeUseTimes((int) lastCumulativeUseTimes);
            eamAssetInfoService.updateById(assetInfo);
        }
        this.updateById(item);
    }
}

